<html>
    <head>
        <meta charset='utf-8'>
        <title>Keep Account</title>
        <link rel="stylesheet" type="text/css" href="res/common.css" /> 
        <style>
            /* #sidebar {
                float: left;
                width: 180px;
                margin-right: 20px;
            } */
            #main_data {
                width: 640px;
                float: left;
            }
            #new_button {
                margin:10px;
            }
            /* .sidebar_item {
                font-size: 18px;
                font-weight: bold;
                cursor: pointer;
                text-align: center;
            } */
        </style>
        <script type="text/javascript" src="res/common.js"></script>
        <script type="text/javascript" src="/res/SimpleTable.js"></script>
        <script type="text/javascript" src="/res/KVPopUpWindows.js"></script>
    </head>
    <body>
        <div id="navi_bar">
        </div>
        <div id="data">
            <div id="sidebar">
                <p class="sidebar_item" onclick="onSidebarItemClicked('sb_payment_cat1');" id="sb_payment_cat1">Payment Cat1</p>
                <p class="sidebar_item" onclick="onSidebarItemClicked('sb_payment_cat2');" id="sb_payment_cat2">Payment Cat2</p>
                <p class="sidebar_item" onclick="onSidebarItemClicked('sb_income_cat1');" id="sb_income_cat1">Income Cat1</p>
                <p class="sidebar_item" onclick="onSidebarItemClicked('sb_transfer_cat1');" id="sb_transfer_cat1">Transfer Cat1</p>
                <p class="sidebar_item" onclick="onSidebarItemClicked('sb_currency');" id="sb_currency">Currency</p>
                <p class="sidebar_item" onclick="onSidebarItemClicked('sb_account');" id="sb_account">Account</p>
            </div>
            <div id="main_data">
                <button id="new_button" onclick="puw_manager.show(sbid_popid[g_current_sidebar_item_id]);">New</button>
                <div id="table_data">
                    <!-- 這裡展示表格 -->
                </div>
            </div>
        </div>
        <div id="pop_up_window">
            <!--弹窗专用-->
        </div>
    </body>
    <script>
        /**
         * 生成表格的行id，返回一个字符串
         * sb_id:       表格所属side_bar的id
         * id:          当前行数据的id
         */
        function genTableRowId(sb_id, id) {
            switch(g_current_sidebar_item_id) {
            case 'sb_payment_cat1':     return 'pc1_id_' + id;
            case 'sb_payment_cat2':     return 'pc2_id_' + id;
            case 'sb_income_cat1':      return 'ic1_id_' + id;
            case 'sb_transfer_cat1':    return 'tc1_id_' + id;
            case 'sb_currency':         return 'crc_id_' + id;
            case 'sb_account':          return 'acnt_id_' + id;
            default:                
                console.log('unknow case: ' + g_current_sidebar_item_id);                 return;
            }
        }

        function getPopUpWindowIdBySideBarId(sb_id) {
            pop_up_window_id = sbid_popid[sb_id];
        }
        
        /**
         * 左側導航欄某個按鈕點擊後的操作
         * 被點擊的按鈕設置為高亮
         * 加載對應的數據，展示在table_data區域
         * sidebar_id: 左侧导航栏标签的id
         */
        function onSidebarItemClicked(sidebar_id) {
            setHighLightSidebarItem(sidebar_id);
            switch(sidebar_id) {
            case 'sb_payment_cat1':     getUrlAsyn('/service/category/getPaymentCat1', onPaymentCat1DataReceived);      break;
            case 'sb_payment_cat2':     getUrlAsyn('/service/category/getPayment', onPaymentCat2DataReceived);          break;
            case 'sb_income_cat1':      getUrlAsyn('/service/category/getIncome', onIncomeCat1DataReceived);            break;
            case 'sb_transfer_cat1':    getUrlAsyn('/service/category/getTransfer', onTransferCat1DataReceived);        break;
            case 'sb_currency':         getUrlAsyn('/service/currency/getAll', onCurrencyDataReceived);                 break;
            case 'sb_account':          getUrlAsyn('/service/account/getAllGroupedByCurrency', onAccountDataReceived);  break;
            default:                    console.log('unknow sidebar_id! ' + sidebar_id);                                return;
            }
        }

        // /**
        //  * 把sidebar_id對應的item設置為高亮的樣式
        //  * 原有的高亮item回復原樣
        //  * 會修改current_sidebar_item_id這個全局變量
        //  */ 
        // function setHighLightSidebarItem(sidebar_id) {
        //     var old_element = document.getElementById(g_current_sidebar_item_id);
        //     var new_element = document.getElementById(sidebar_id);
        //     old_element.style.borderRadius = '';
        //     old_element.style.backgroundColor = '';
        //     old_element.style.disable = 'false';
        //     new_element.style.borderRadius = '20px';
        //     new_element.style.backgroundColor = 'gold';
        //     new_element.style.disable = 'true';
        //     g_current_sidebar_item_id = sidebar_id;
        // }

        // 把一个对象数组，按照指定的key_name，转换成{key:obj}的map 
        // 返回map
        function objectList2Map(obj_list, key_name) {
            ret = {};
            obj_list.forEach(function(ele) {
                key = ele[key_name];
                ret[key] = ele;
            });
            return ret;
        }

        function onCurrencyDataReceived(result) {
            result = JSON.parse(result);
            g_table_ori_data = objectList2Map(result.data, 'crc_id');
            g_table.clear();
            g_table.setHeader(['ID', 'Name', 'Unit', 'Character', 'Operation']);
            result.data.forEach(function(ele) {
                row_id = genTableRowId('sb_currency', ele.crc_id);
                operationContent = genOperationContent('editOperationCollection', 'deleteOperationCollection', ele.crc_id);
                g_table.addRow([ele.crc_id.toString(), ele.nameme, ele.unit, ele.characterter, operationContent], row_id);
            });

            g_table.show();
        }

        function onAccountDataReceived(result) {
            result = JSON.parse(result);
            g_table_ori_data = {};
            result.data.forEach(function(ele) {
                Object.assign(g_table_ori_data, objectList2Map(ele.account_list, 'acnt_id'));
            });
            // 生成复杂格式的账户表格
            g_table.clear();
            g_table.setHeader(['ID', 'Currency', 'Account Name', 'Operation']);
            result.data.forEach(function(ele) {
                is_first_loop = true;
                ele.account_list.forEach(function(ele2) {
                    operationContent = genOperationContent('editOperationCollection', 'deleteOperationCollection', ele2.acnt_id);
                    if(is_first_loop == true) {
                        g_table.addRow([ele2.crc_id.toString(), {'text':ele.nameme, 'colspan':1, 'rowspan':ele.account_list.length}, ele2.nameme, operationContent]);
                        is_first_loop = false;
                    }
                    else {
                        g_table.addRow([ele2.crc_id.toString(), ele2.nameme, operationContent]);
                    }
                });
            });
            // 更新弹窗中的crc_id的选项
            select_items = [];
            result.data.forEach(function(ele) {
                select_items.push({'name':ele.nameme, 'value':ele.crc_id});
            });
            pop_up_window.setComboBoxItems('account_popup_crc_id_select', select_items);
            g_table.show();
        }

        function onIncomeCat1DataReceived(result) {
            result = JSON.parse(result);
            g_table_ori_data = objectList2Map(result.data, 'cat1_id');
            g_table.clear();
            g_table.setHeader(['ID', 'Name', 'Operation']);
            result.data.forEach(function(ele) {
                operationContent = genOperationContent('editOperationCollection', 'deleteOperationCollection', ele.cat1_id);
                g_table.addRow([ele.cat1_id.toString(), ele.nameme, operationContent]);
            });

            g_table.show();
        }

        function onPaymentCat1DataReceived(result) {
            result = JSON.parse(result);
            g_table_ori_data = objectList2Map(result.data, 'cat1_id');
            g_table.clear();
            g_table.setHeader(['ID', 'Name', 'Operation']);
            result.data.forEach(function(ele) {
                operationContent = genOperationContent('editOperationCollection', 'deleteOperationCollection', ele.cat1_id);
                row_id = genTableRowId('sb_payment_cat1', ele.cat1_id);
                g_table.addRow([ele.cat1_id.toString(), ele.nameme, operationContent], row_id);
            });

            g_table.show();
        }

        /** 
         * 收到Payment数据后，绘制表格，并且修改New弹窗中的ComboBox的内容
         * 注意，Cat1 Name这一列用到了复杂表格（合并单元格）
         */
        function onPaymentCat2DataReceived(result) {
            result = JSON.parse(result);
            g_table_ori_data = {};
            result.data.forEach(function(ele) {
                Object.assign(g_table_ori_data, objectList2Map(ele.cat2_list, 'cat2_id'));
            });
            // 绘制表格
            g_table.clear();
            g_table.setHeader(['ID', 'Cat1 Name', 'Cat2 Name', 'ShortNames', 'Operation']);
            result.data.forEach(function(ele) {
                is_first_loop = true;
                ele.cat2_list.forEach(function(ele2) {
                    operationContent = genOperationContent('editOperationCollection', 'deleteOperationCollection', ele2.cat2_id);
                    if(is_first_loop == true) {
                        g_table.addRow([ele2.cat2_id.toString(), {'text':ele.nameme, 'colspan':1, 'rowspan':ele.cat2_list.length}, ele2.nameme, ele2.short_names, operationContent]);
                        is_first_loop = false;
                    }
                    else {
                        g_table.addRow([ele2.cat2_id.toString(), ele2.nameme, ele2.short_names, operationContent]);
                    }
                });
            });
            // 修改New弹窗的ComboBox的内容
            select_items = [];
            result.data.forEach(function(ele){
                select_items.push({'name':ele.nameme, 'value':ele.cat1_id});
            });
            pop_up_window = puw_manager.getPopUpWindowObject('payment_cat2_popup');
            pop_up_window.setComboBoxItems('payment_cat2_popup_cat1_id_select', select_items);
            g_table.show();
        }

        function onTransferCat1DataReceived(result) {
            result = JSON.parse(result);
            g_table_ori_data = objectList2Map(result.data, 'cat1_id');
            g_table.clear();
            g_table.setHeader(['ID', 'Name', 'Operation']);
            result.data.forEach(function(ele) {
                operationContent = genOperationContent('editOperationCollection', 'deleteOperationCollection', ele.cat1_id);
                g_table.addRow([ele.cat1_id.toString(), ele.nameme, operationContent]);
            });

            g_table.show();
        }

        /**
         * 生成表格Operation列的内容
         * 即：编辑按钮和删除按钮的HTML代码
         * edit_callback:   编辑功能的回调函数，参数为:(id)
         * del_callback:    删除功能的回调函数，参数为:(id)
         * 返回生成后的HTML代码
         */
        function genOperationContent(edit_callback, del_callback, id) {
            return '<a style="padding:0px 10px 0px 10px;" href="javascript:void(0);" onclick="' + edit_callback + '(' + id + ')">Edit</a>' 
                +  '<a style="padding:0px 10px 0px 10px;" href="javascript:void(0);" onclick="' + del_callback + '(' + id + ')">Delete</a>';
        }

        // 所有编辑操作统一在这里处理
        function editOperationCollection(id) {
            old_data = g_table_ori_data[id];
            title = '';
            pop_up_window = puw_manager.getPopUpWindowObject('edit_pop_up');
            pop_up_window.deleteAllItems();
            switch(g_current_sidebar_item_id) {
            case 'sb_payment_cat1':     pop_up_window.addTextarea('Name: ', 'nameme', old_data.nameme); break;
            case 'sb_income_cat1':      pop_up_window.addTextarea('Name: ', 'nameme', old_data.nameme); break;
            case 'sb_transfer_cat1':    pop_up_window.addTextarea('Name: ', 'nameme', old_data.nameme); break;
            case 'sb_account':          pop_up_window.addTextarea('Name: ', 'nameme', old_data.nameme); break;
            case 'sb_currency':
                pop_up_window.addTextarea('Name: ', 'nameme', old_data.nameme);
                pop_up_window.addTextarea('Unit: ', 'unit', old_data.unit);
                pop_up_window.addTextarea('Character: ', 'characterter', old_data.characterter);        break;
            case 'sb_payment_cat2':
                pop_up_window.addTextarea('Name: ', 'nameme', old_data.nameme);
                pop_up_window.addTextarea('Short Names:', 'short_names', old_data.short_names);         break;
            default:                    console.log('unknow case: ' + g_current_sidebar_item_id);         return;
            }
            pop_up_window.setAppendixData('id', id);
            puw_manager.show('edit_pop_up');
        }

        function editOperationCallback(pop_up_window_id) {
            pop_up_window = puw_manager.getPopUpWindowObject(pop_up_window_id);
            data = pop_up_window.getAllItems();
            switch(g_current_sidebar_item_id) {
            case 'sb_payment_cat1':     uri = '/service/category/editPaymentCat1?cat1_id=' + data.id + '&nameme=' + data.nameme;    break;
            case 'sb_income_cat1':      uri = '/service/category/editIncome?cat1_id=' + data.id + '&nameme=' + data.nameme;     break;
            case 'sb_transfer_cat1':    uri = '/service/category/editTransfer?cat1_id=' + data.id + '&nameme=' + data.nameme;   break;
            case 'sb_account':          uri = '/service/account/edit?acnt_id=' + data.id + '&nameme=' + data.nameme;                break;
            case 'sb_payment_cat2':     
                uri = '/service/category/editPaymentCat2?cat2_id=' + data.id + '&nameme=' + data.nameme + '&short_names=' + data.short_names;
                break;
            case 'sb_currency':         
                uri = '/service/currency/edit?crc_id=' + data.id + '&nameme=' + data.nameme + '&unit=' + data.unit + '&characterter=' + data.characterter;
                break;
            default:                    console.log('unknow case: ' + g_current_sidebar_item_id);                                     return;
            }
            getUrlAsyn2(uri, onEditOperationFinished);
        }

        function onEditOperationFinished(result) {
            if(result.status != 200
            || result.response.errno != 0) {
                alert('Edit Failed!\n' + JSON.stringify(result));
                return;
            }
            alert('ok!');
            onSidebarItemClicked(g_current_sidebar_item_id);
            puw_manager.close('edit_pop_up');
            // 编辑弹窗的内容不用清空，下次使用的时候会删除弹窗内容
        }

        // 所有删除操作统一在这里处理
        function deleteOperationCollection(id) {
            if(confirm("Are you sure to delete this?") == false) {
                return;
            }
            switch(g_current_sidebar_item_id) {
            case 'sb_payment_cat1':     uri = '/service/category/deletePaymentCat1?cat1_id=' + id;  break;
            case 'sb_payment_cat2':     uri = '/service/category/deletePaymentCat2?cat2_id=' + id;  break;
            case 'sb_income_cat1':      uri = '/service/category/deleteIncomeCat1?cat1_id=' + id;   break;
            case 'sb_transfer_cat1':    uri = '/service/category/deleteTransferCat1?cat1_id=' + id; break;
            case 'sb_currency':         uri = '/service/currency/delete?crc_id=' + id;              break;
            case 'sb_account':          uri = '/service/account/delete?acnt_id=' + id;              break;
            default:                    console.log('unknow case: ' + g_current_sidebar_item_id);     return;
            }
            getUrlAsyn2(uri, onDeleteOperationFinished);
        }

        // 删除操作结束时的回调函数
        function onDeleteOperationFinished(result) {
            switch(g_current_sidebar_item_id) {
            case 'sb_payment_cat1':     operation_name = 'Delete payment category1';    break;
            case 'sb_payment_cat2':     operation_name = 'Delete payment category2';    break;
            case 'sb_income_cat1':      operation_name = 'Delete income category';      break;
            case 'sb_transfer_cat1':    operation_name = 'Delete transfer category';    break;
            case 'sb_currency':         operation_name = 'Delete currency';             break;
            case 'sb_account':          operation_name = 'Delete account';              break;
            default:                    console.log('unknow case: ' + g_current_sidebar_item_id); return;
            }
            if(result.status != 200
            || result.response.errno != 0) {
                alert(operation_name + ' failed!\n' + JSON.stringify(result));
                return;
            }
            alert('ok!');
            onSidebarItemClicked(g_current_sidebar_item_id);
        }

        // 新建操作弹窗提交后的回调函数
        // 根据当前菜单名称，发送不同的URL请求
        function newOperationCallback(pop_up_window_id) {
            pop_up_window = puw_manager.getPopUpWindowObject(pop_up_window_id);
            kv_data = pop_up_window.getAllItems();
            switch(g_current_sidebar_item_id) {
            case 'sb_payment_cat1':     
                uri = '/service/category/addPaymentCat1?nameme=' + kv_data['nameme'];
                break;
            case 'sb_payment_cat2':     
                uri = '/service/category/addPaymentCat2?nameme=' + kv_data['nameme'] + '&cat1_id=' 
                    + kv_data['cat1_id'] + '&short_names=' + kv_data['short_names']; 
                break;
            case 'sb_income_cat1':
                uri = '/service/category/addIncome?nameme=' + kv_data['nameme'];  
                break;
            case 'sb_transfer_cat1':
                uri = '/service/category/addTransfer?nameme=' + kv_data['nameme'];  
                break;
            case 'sb_currency':         
                uri = '/service/currency/add?nameme=' + kv_data.nameme + '&unit=' + kv_data.unit
                    + '&characterter=' + kv_data.characterter; 
                break;
            case 'sb_account':         
                uri = '/service/account/add?crc_id=' + kv_data.crc_id + '&typepe=' + kv_data.typepe 
                    + '&nameme=' + kv_data.nameme + '&descriptiontion=' + kv_data.descriptiontion;
                break;
            default:                
                console.log('unknow case: ' + g_current_sidebar_item_id);                 return;
            }
            getUrlAsyn2(uri, onNewOperationFinished);
            pop_up_window.clearAllItems();
        }

        // 新建操作结束后的回调函数
        function onNewOperationFinished(result) {            
            switch(g_current_sidebar_item_id) {
            case 'sb_payment_cat1':     operation_name = 'Add new payment category1'; pop_up_window_id = 'payment_cat1_popup';  break;
            case 'sb_payment_cat2':     operation_name = 'Add new payment category2'; pop_up_window_id = 'payment_cat2_popup';  break;
            case 'sb_income_cat1':      operation_name = 'Add new income category'; pop_up_window_id = 'income_cat1_popup';      break;
            case 'sb_transfer_cat1':    operation_name = 'Add new transfer category'; pop_up_window_id = 'transfer_cat1_popup'; break;
            case 'sb_currency':         operation_name = 'Add new currency'; pop_up_window_id = 'currency_popup';                   break;
            case 'sb_account':          operation_name = 'Add new account'; pop_up_window_id = 'account_popup';                      break;
            default:                    console.log('unknow case: ' + g_current_sidebar_item_id);                                                                     return;
            }
            if(result.status != 200
            || result.response.errno != 0) {
                alert(operation_name + ' failed!\n' + JSON.stringify(result));
                return;
            }
            alert('ok!');
            onSidebarItemClicked(g_current_sidebar_item_id);
            puw_manager.close(pop_up_window_id);
        }

        g_current_sidebar_item_id = 'sb_payment_cat1';
        var sbid_popid = {
            'sb_payment_cat1'   :   'payment_cat1_popup',
            'sb_payment_cat2'   :   'payment_cat2_popup',
            'sb_income_cat1'    :   'income_cat1_popup',
            'sb_transfer_cat1'  :   'transfer_cat1_popup',
            'sb_currency'       :   'currency_popup',
            'sb_account'        :   'account_popup',
        };
        var g_table_ori_data = {};  // 每个子页面的表格的数据来源
        var g_table = new SimpleTable('data_table', 'table_data');
        genNavBar('management');
        
        // 创建一系列的弹窗
        var puw_manager = new KVPopUpWindowManager('pop_up_window')
        pop_up_window = puw_manager.createPopUpWindow('payment_cat1_popup', 'New Payment Cat1', 'newOperationCallback');
        pop_up_window.addTextarea('Name:', 'nameme', '');
        pop_up_window = puw_manager.createPopUpWindow('payment_cat2_popup', 'New Payment Cat2', 'newOperationCallback');
        pop_up_window.addTextarea('Name:', 'nameme', '');
        pop_up_window.addEmptyComboBox('payment_cat2_popup_cat1_id_select', 'cat1_id', 'Cat1:');
        pop_up_window.addTextarea('Short Names:', 'short_names', '');
        pop_up_window = puw_manager.createPopUpWindow('income_cat1_popup', 'New Income Cat', 'newOperationCallback');
        pop_up_window.addTextarea('Name:', 'nameme', '');
        pop_up_window = puw_manager.createPopUpWindow('transfer_cat1_popup', 'New Transfer Cat', 'newOperationCallback');
        pop_up_window.addTextarea('Name:', 'nameme', '');
        pop_up_window = puw_manager.createPopUpWindow('currency_popup', 'New Currency', 'newOperationCallback');
        pop_up_window.addTextarea('Name:', 'nameme', '');
        pop_up_window.addTextarea('Unit:', 'unit', '');
        pop_up_window.addTextarea('Character:', 'characterter', '');
        pop_up_window = puw_manager.createPopUpWindow('account_popup', 'New Account', 'newOperationCallback');
        pop_up_window.addEmptyComboBox('account_popup_crc_id_select', 'crc_id', 'Currency:');
        pop_up_window.addEmptyComboBox('account_popup_type_select', 'typepe', 'Type:');
        pop_up_window.setComboBoxItems('account_popup_type_select', [{'name':'Normal','value':1},{'name':'Debet','value':2},{'name':'Loan','value':3}]);
        pop_up_window.addTextarea('Name:', 'nameme', '');
        pop_up_window.addTextarea('Description:', 'descriptiontion', '');
        puw_manager.createPopUpWindow('edit_pop_up', 'Edit', 'editOperationCallback');

        // 设置默认选定的功能
        onSidebarItemClicked(g_current_sidebar_item_id);

    </script>
</html>
